package Servlet;

import Service.GetTableName;
import Service.GetTableService;
import dto.Table;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/GetTableServlet")
public class GetTableServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tableName = req.getParameter("tableName");
        GetTableService getTableService = new GetTableService();
        GetTableName getTableName = new GetTableName();
        try {
            List<String> tableNames = getTableName.GetTableName(req, resp);
            if (tableName == null) {
                tableName = tableNames.get(0);
            }
            Table table = getTableService.GetTableService(req, resp, tableName);
            req.setAttribute("tableNames", tableNames);
            req.setAttribute("table", table);
            RequestDispatcher dispatcher = req.getRequestDispatcher("index.jsp");
            dispatcher.forward(req, resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
